package com.upup.train_management.controller;

import com.upup.train_management.entity.Ticket;
import com.upup.train_management.entity.User;
import com.upup.train_management.service.BookingService;
import com.upup.train_management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/booking")
public class BookingController {

    private final BookingService bookingService;
    private final UserService userService;

    @Autowired
    public BookingController(BookingService bookingService, UserService userService) {
        this.bookingService = bookingService;
        this.userService = userService;
    }

    @PostMapping
    public ResponseEntity<?> bookTicket(@RequestBody Ticket ticket) {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }

        // 设置当前用户ID
        ticket.setUserId(currentUser.getId());

        try {
            Ticket bookedTicket = bookingService.bookTicket(ticket);
            return ResponseEntity.ok(bookedTicket);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/{ticketId}/cancel")
    public ResponseEntity<?> cancelBooking(@PathVariable Long ticketId) {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).build();
        }

        try {
            boolean cancelled = bookingService.cancelBooking(ticketId, currentUser.getId());
            if (cancelled) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.badRequest().body("取消预订失败");
            }
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/check-availability/{scheduleId}")
    public ResponseEntity<Boolean> checkAvailability(@PathVariable Long scheduleId) {
        boolean available = bookingService.checkAvailability(scheduleId);
        return ResponseEntity.ok(available);
    }    private User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || 
            "anonymousUser".equals(authentication.getName())) {
            return null;
        }
        
        User user = userService.getUserByUsername(authentication.getName());
        // 额外验证：确保用户对象有效且有必要的字段
        if (user == null || user.getUsername() == null || user.getUsername().isEmpty()) {
            return null;
        }
        
        return user;
    }
}